(ns cl-slika.models.user
  (:require 
    [simpledb.core :as db]
         [noir.util.crypt :as crypt]
            [noir.validation :as vali]
            [noir.session :as session]   
            [noir.cookies :as cookie]
        ))

(defn get-username [username]
  (db/get-in :users [username]))


(defn me []
  (session/get :username))

(defn logout []
 (do
      (cookie/put! :username "")
        (session/put! :username nil)))

;; Mutations and Checks

(defn prepare [{password :password :as user}]
  (assoc user :password (crypt/encrypt password)))

(defn valid-user? [username]
  (vali/rule (not (db/get-in :users [username]))
             [:username "That username is already taken"])
  (vali/rule (vali/min-length? username 3)
             [:username "Username must be at least 3 characters."])
 
  (not (vali/errors? :username :password)))

(defn valid-psw? [password]
  (vali/rule (vali/min-length? password 5)
             [:password "Password must be at least 5 characters."])
  (not (vali/errors? :password)))

;; Operations

(defn- store! [{username :username :as user}]
  (db/update! :users assoc username user)
  )

(defn- copass [username]
   (cookie/put! :username username)
        (session/put! :username username)
  )

(defn login! [{:keys [username password] :as user}]
  
  (let [u (get-username username)
        {stored-pass :password} u]
 
    (if (and stored-pass 
             (crypt/compare password stored-pass))
      (copass username)
      
        (str "Invalid username or password")
        
      )))

(defn add! [{:keys [username passwordR] :as user}]
 
  (let [user1 (assoc {} :username (:username user) :mail (:mail user) :password (:passwordR user))]
 
  (when (valid-user? username)
    (when (valid-psw? passwordR)
      (when (-> user1 (prepare) (store!))
          (copass username)    )
       ))
  (str (vali/errors? :username :passwordR))
  )
  )


(defn init! []
    (db/put! :users {})
    (store! (prepare {:username "admin" :password "admin"})))

